package com.book.controller.admin;

import com.book.pojo.Admin;
import com.book.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    // 登录
    @PostMapping("/login")
    @ResponseBody
    public String toLogin(Admin admin, HttpSession session, Model model){
        return adminService.loginCheck(admin, session);
    }

    // 注销
    @GetMapping("/logout")
    public String toLogout(HttpSession session){
        session.invalidate();
        return "redirect:/admin";
    }

    // index页面
    // 注销
    @GetMapping("/index")
    public String toIndex(){
        return "admin/index";
    }

    // 查询所有
    // 获取用户列表
    @GetMapping("/list")
    public String list(Model model){

        List<Admin> adminList = adminService.list();

        model.addAttribute("adminList", adminList);

        return "admin/admins_list";
    }

    // 删除
    @GetMapping("/toDelete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        adminService.removeById(id);
        return "redirect:/admin/list";
    }

    // 跳转到修改页面
    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model){

        Admin admin = adminService.getById(id);

        model.addAttribute("admins", admin);

        return "admin/admins_update";
    }


    // 修改
    @PostMapping("/update")
    public String update(Admin admin){
        adminService.updateById(admin);
        return "redirect:/admin/list";
    }

    // 跳转到添加页面
    @GetMapping("/addShow")
    public String toAddShow(){
        return "admin/admins_add";
    }


    // 添加
    @PostMapping("/add")
    public String add(Admin admin){
        adminService.save(admin);
        return "redirect:/admin/list";
    }
}
